package com.example.fufudamowang.mus;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import data.Music;
import data.MusicList;





public class MainActivity extends AppCompatActivity {

    private ImageButton imb_last;
    private ImageButton imb_begin;
    private ImageButton imb_stop;
    private ImageButton imb_next;
    private ListView list;

    //歌曲列表对象
    private ArrayList<Music>musicArrayList;

    //歌曲序号
    private int number=0;

    //媒体播放类
    private MediaPlayer player;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        player=new MediaPlayer();
//
        findViews();
        registerListenters();
        initMusicList();
        initListView();
        checkMusicfile();
    }



    //对应组件
    private void findViews() {
        imb_last=(ImageButton)findViewById(R.id.imageButton_last);
        imb_begin=(ImageButton)findViewById(R.id.imageButton_begin);
        imb_stop=(ImageButton)findViewById(R.id.imageButton_stop);
        imb_next=(ImageButton)findViewById(R.id.imageButton_next);
        list = (ListView) findViewById(R.id.LV);
    }
    //为显示组件注册监听器
    private void registerListenters() {
        imb_last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                numbertoLast();
                play(number);
                //按键背景设置
                imb_begin.setBackgroundResource(R.drawable.button_pause);

            }
        });

        imb_begin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (player != null && player.isPlaying()) {
                    pause();
                    imb_begin.setBackgroundResource(R.drawable.button_begin);
                } else {
                    play(number);
                    imb_begin.setBackgroundResource(R.drawable.button_pause);
                }
            }
        });

        imb_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stop();
                imb_begin.setBackgroundResource(R.drawable.button_begin);
            }
        });

        imb_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                numbertoNext();
                play(number);
                imb_begin.setBackgroundResource(R.drawable.button_pause);
            }
        });

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number = position;
                play(number);
                imb_begin.setBackgroundResource(R.drawable.button_pause);
            }
        });
    }



    //初始化音乐列表对象
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        //避免重复添加音乐
        if(musicArrayList.isEmpty())
        {
            //使用ContentProvider,对应ContentResolver
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载带ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>"))//如果艺术家字段为unknown
                    strArtist = "无艺术家";
                Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                musicArrayList.add(music);
            }
        }
    }
//使用SimpleAdapter适配器把数据绑定到视图
    //适配器还有BaseAdapter、SimpleAdapter和ArrayAdapter
    private void initListView(){
        List<Map<String,String>>list_map=new ArrayList<Map<String, String>>();
        HashMap<String,String>map;
        SimpleAdapter simpleAdapter;
        for(Music music : musicArrayList){
            map=new HashMap<String,String>();
            map.put("musicName",music.getMusicName());
            map.put("musicArtist",music.getMusicArtist());
            list_map.add(map);

        }
        String[] from =new String[]{"musicName","musicArtist"};
        int[] to={R.id.tv_title,R.id.tv_artist};


        simpleAdapter=new SimpleAdapter(this,list_map,R.layout.listview,from,to);
        list.setAdapter(simpleAdapter);
    }

    /**如果列表没有歌曲，则播放按钮不可用，并提醒用户*/
    private void checkMusicfile()
    {
        if (musicArrayList.isEmpty()) {
            imb_next.setEnabled(false);
            imb_begin.setEnabled(false);
            imb_last.setEnabled(false);
            imb_stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "没有歌曲文件",Toast.LENGTH_SHORT).show();
        } else {
            imb_next.setEnabled(true);
            imb_begin.setEnabled(true);
            imb_last.setEnabled(true);
            imb_stop.setEnabled(true);
        }
    }


    //读取音乐文件
   private void load(int number){
       try{
           player.reset();//release不可以
           player.setDataSource(musicArrayList.get(number).getMusicPath());//准备音频
           player.prepare();
       }catch (Exception e) {
           e.printStackTrace();
       }

   }


    //播放
    private  void play(int number){
        //停止
        if(player!=null&&player.isPlaying()){
            player.stop();
        }
        load(number);
        player.start();

    }

    private  void pause() {
        if(player.isPlaying())
            player.pause();
    }

    private void stop(){
        player.stop();
    }

    //暂停之后，恢复播放
    private void resume(){
        player.start();
    }


    //从新播放
    private void replay(){
        player.start();
    }
    private void numbertoLast() {
        if(number==0){
            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_top),Toast.LENGTH_SHORT).show();
        }
        else
        {
            number--;
            play(number);
        }
    }
    private void numbertoNext(){
        if(number== MusicList.getMusicList().size()-1)
            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_bottom),Toast.LENGTH_SHORT).show();
        else
        {
            number++;
            play(number);
        }
    }

}
